package cn.edu.gzccc.chpater421.controller;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component//注册到DemoApplication 这个Spring容器中
@Aspect//LogAspect类是切面类
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(LogAspect.class);


    //切入点
    @Pointcut("execution(public * cn.edu.gzccc.chpater421.controller.HelloController.*(..))")
    public void cut(){}

    //调用前执行
    @Before("cut()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =  attributes.getRequest();
        //url
        logger.info("url ={}",request.getRequestURI());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //类方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+'.'+ joinPoint.getSignature().getName());//获取类名及类方法
        //参数
        logger.info("args={}",joinPoint.getArgs());
        //System.out.println("调用开始时间: " + Calendar.getInstance().getTimeInMillis());
    }

    //调用后执行
    @After("cut()")
    public void doAfter(){
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> doAfter");
    }
    @AfterReturning(returning = "obj",pointcut = "cut()")//在调用上面 @Pointcut标注的方法后执行。用于获取返回值
    public void doAfterReturning(Object obj){
        logger.info("response={}",obj.toString());
    }

}
